$(function () {
	initialPage();
	getGrid();
//     $("#jqGrid").Grid({
//         url: '../tbVideoCategory/list',
//         colModel: [
//         {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
//     			{label: 'icon', name: '分类图标', index: 'icon', width: 80},
//     			{label: 'name', name: '分类名称', index: 'name', width: 80},
//     			// {label: 'parentId', name: 'parentId', index: 'parentId', width: 80},
//     			{label: 'sort', name: '排序号', index: 'sort', width: 80},
// ]
//     });
});
function initialPage() {
	$(window).resize(function () {
		TreeGrid.table.resetHeight({height: $(window).height() - 100});
	});

}
function getGrid() {
	var colunms = TreeGrid.initColumn();
	var table = new TreeTable(TreeGrid.id, '../tbVideoCategory/queryAll', colunms);
	table.setExpandColumn(2);
	table.setIdField("id");
	table.setCodeField("id");
	table.setParentCodeField("parentId");
	table.setExpandAll(false);
	table.setHeight($(window).height() - 100);
	table.init();
	TreeGrid.table = table;
}
var TreeGrid = {
	id: "jqGrid",
	table: null,
	layerIndex: -1
};
TreeGrid.initColumn = function () {
	var columns = [
		{field: 'selectItem', radio: true},
		{title: '编号', field: 'id', align: 'id', width: '50px'},
		{title: '分类名称', field: 'name', align: 'center', valign: 'middle', width: '100px'},
		{
			title: '分类图标',
			field: 'icon',
			align: 'center',
			valign: 'middle',
			width: '150px',
			formatter: function (cellvalue, options, rowObject) {

				if (cellvalue.icon!=null) {
					return '<img src="' + cellvalue.icon + '"  style="width:50px;height:50px;" />'
				}
			}
		},
		{title: '类别', field: 'level', align: 'center', valign: 'middle', width: '50px',formatter:function  (cellvalue, options, rowObject) {
				console.log(cellvalue);
				if (cellvalue.level===0){
					return '<span class="label label-success">一级分类</span>';
				}else if(cellvalue.level===1){
					return '<span class="label label-primary">二级分类</span>';
				}
			}},
		{title: '排序号', field: 'sort', align: 'center', valign: 'middle', width: '50px'}

		]
	return columns;
};
var setting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "id",
			pIdKey: "parentId",
			rootPId: 0
		},
		key: {
			url: "nourl"
		}
	}
};

var ztree;
var ztree2;

let vm = new Vue({
	el: '#rrapp',
	data: {
		addFrom:false,
        showList: true,
		updateFrom:false,
        title: null,
		tbVideoCategory: {
			id:0
		},
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},
		q: {
		    name: ''
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.updateFrom=false;
			vm.addFrom=true;
			vm.showList = false;
			vm.title = "新增";
			vm.tbVideoCategory = {
				name:"",
				parentId:"",
				sort:0,
				icon:"",
				parentName:"",
				level:0
			};
			var menuId = TreeGrid.table.getSelectedRow();
			console.log("menuid"+menuId[0].id);
			if (menuId.length!=0){
				vm.tbVideoCategory.level=1;
				vm.tbVideoCategory.parentId=menuId[0].id;
			}
			this.getMenu(menuId);
		},
		update: function (event) {
			vm.addFrom=false;
			vm.updateFrom=true;
			var menuId = TreeGrid.table.getSelectedRow();
			if (menuId.length == 0) {
				iview.Message.error("请选择一条记录");
				return;
			}
			vm.showList = false;
            vm.title = "修改";


			Ajax.request({
				url: "../tbVideoCategory/info/" + menuId[0].id,
				// async: true,
				successCallback: function (r) {
					vm.showList = false;
					vm.title = "修改";
					// vm.load();
					vm.tbVideoCategory = r.tbVideoCategory;
					console.log("-------------");
					console.log(vm.tbVideoCategory);
					// vm.showDesc(r.menu.type);
					// r.tbVideoCategory.goodsSpecification.forEach((item,index)=>{
					// 	vm.selectSpec(index)
					// })
				}
			});
			vm.getMenu();
		},
		menuTree: function () {
			openWindow({
				title: "选择菜单",
				area: ['300px', '450px'],
				content: jQuery("#menuLayer"),
				btn: ['确定', '取消'],
				// btn: ['取消'],
				btn2: function (index) {
					var node = ztree.getSelectedNodes();
					//选择上级菜单
					vm.tbVideoCategory.parentId = node[0].id;
					vm.tbVideoCategory.parentName = node[0].name;

					layer.close(index);
				}
			});
		},
		saveOrUpdate: function (event) {
			let url="";
			let menuId = TreeGrid.table.getSelectedRow();
			console.log(menuId);
			Ajax.request({
			    url: "../tbVideoCategory/save",
                params: JSON.stringify(vm.tbVideoCategory),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		updateFromAction:function(){
			let menuId = TreeGrid.table.getSelectedRow();
			console.log(menuId);
			Ajax.request({
				url: "../tbVideoCategory/update",
				params: JSON.stringify(vm.tbVideoCategory),
				type: "POST",
				contentType: "application/json",
				successCallback: function (r) {
					alert('操作成功', function (index) {
						vm.reload();
					});
				}
			});
		},
		getMenu: function (menuId) {
			//加载菜单树
			Ajax.request({
				url: "../tbVideoCategory/queryAll",
				async: true,
				successCallback: function (r) {
					ztree = $.fn.zTree.init($("#menuTree"), setting, r.list);
					console.log(ztree);
					var node = ztree.getNodeByParam("id", vm.tbVideoCategory.parentId);

					if (node) {
						ztree.selectNode(node);
						vm.tbVideoCategory.parentName = node.name;
					} else {
						node = ztree.getNodeByParam("id", 0);
						ztree.selectNode(node);
						vm.tbVideoCategory.parentName = node.name;
					}
				}
			});
		},
		del: function (event) {
			var menuIds = TreeGrid.table.getSelectedRow(), ids = [];
			confirm('确定要删除选中的记录？', function () {
				$.each(menuIds, function (idx, item) {
					ids[idx] = item.id;
				});
                Ajax.request({
				    url: "../tbVideoCategory/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(id){
            Ajax.request({
                url: "../tbVideoCategory/info/"+id,
                async: true,
                successCallback: function (r) {
                    vm.tbVideoCategory = r.tbVideoCategory;
                }
            });
		},
		reload: function (event) {
			vm.updateFrom=false;
			vm.saveForm=false;
			vm.showList = true;
			TreeGrid.table.refresh();
		},
        reloadSearch: function() {
            vm.q = {
                name: ''
            }
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },

		handleMaxSize: function (file) {
			this.$Notice.warning({
				title: '超出文件大小限制',
				desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
			});
		},

		handleSuccessListPicUrl: function (res, file) {
			vm.tbVideoCategory.icon = file.response.url;
		},
		eyeImagePicUrl: function () {
			var url = vm.tbVideoCategory.icon;
			eyeImage(url);
		},
		eyeImageListPicUrl: function () {
			var url = vm.goods.listPicUrl;
			eyeImage(url);
		},
		eyeImage: function (e) {
			eyeImage($(e.target).attr('src'));
		},
		handleRemove: function (file) {
			// 从 upload 实例删除数据
			const fileList = this.uploadList;
			this.uploadList.splice(fileList.indexOf(file), 1);
		},
		handleSuccess: function (res, file) {
			// 因为上传过程为实例，这里模拟添加 url
			file.imgUrl = res.url;
			file.name = res.url;
			vm.uploadList.add(file);
		},
		handleSuccessPicUrl: function (res, file) {
			vm.tbVideoCategory.icon = file.response.url;
		},

		handleBeforeUpload: function () {
			const check = this.uploadList.length < 5;
			if (!check) {
				this.$Notice.warning({
					title: '最多只能上传 5 张图片。'
				});
			}
			return check;
		},
		handleFormatError: function (file) {
			this.$Notice.warning({
				title: '文件格式不正确',
				desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
			});
		},
	}
});